import { useEffect, useRef, useState } from "react";
import {
  Button,
  Card,
  Drawer,
  Form,
  Input,
  Space,
  Select,
  Spin,
  Tabs,
  Row,
  Col,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import packageRuleService, {
  type PageListReq,
} from "@/api/services/mes/packageRuleService";
import type { MesPackageRule } from "./entity";
import { toast } from "sonner";
import { t } from "@/locales/i18n";
import useDictionary from "@/hooks/system/useDictionary";
import TableDictTag from "@/components/grid/TableDictTag";
import MesPackageRuleMaterialPage, {
  type MesPackageRuleMaterialHandles,
} from "./material";
import MesPackageRuleTierPage, { type MesPackageRuleTierHandles } from "./tier";
import CustomTable from "@/components/grid/CustomTable";

export default function MesPackageRulePage() {
  const materialRef = useRef<MesPackageRuleMaterialHandles>(null);
  const tierRef = useRef<MesPackageRuleTierHandles>(null);

  const [loading, setLoading] = useState(false);
  const [submitLoading, setSubmitLoading] = useState(false);
  const [queryParams, setQueryParams] = useState<PageListReq>({
    code: undefined,
    name: undefined,
    type: undefined,
    page: 1,
    pageSize: 10,
  });
  const [total, setTotal] = useState(0);
  const [list, setList] = useState<MesPackageRule[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [editingData, setEditingData] = useState<MesPackageRule | null>(null);
  const [form] = Form.useForm();
  const [isView, setIsView] = useState(true);

  //动态设置表格高度
  const [tableScrollY, setTableScrollY] = useState(0);
  const PAGE_OFFSET_HEIGHT = 405;
  const updateTableHeight = () => {
    const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
    setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
  };

  useEffect(() => {
    updateTableHeight(); // 初始化
    window.addEventListener("resize", updateTableHeight);
    return () => window.removeEventListener("resize", updateTableHeight);
  }, []);

  const typeOptions = useDictionary("package_rule_type");

  const columns: ColumnsType<MesPackageRule> = [
    {
      title: "规则编码",
      width: 120,
      key: "code",
      dataIndex: "code",
    },
    {
      title: "规则名称",
      width: 120,
      key: "name",
      dataIndex: "name",
    },
    {
      title: "规则类型",
      width: 120,
      key: "type",
      dataIndex: "type",
      render: (_, record) => (
        <TableDictTag dictCode="package_rule_type" value={record.type ?? ""} />
      ),
    },
    {
      title: "描述",
      width: 120,
      key: "remark",
      dataIndex: "remark",
    },
    {
      title: "操作",
      fixed: "right",
      key: "operation",
      align: "center",
      width: 100,
      render: (_, record) => (
        <Space>
          <Button type="link" onClick={() => handleView(record)}>
            {t("common.view")}
          </Button>
          <Button type="link" onClick={() => handleEdit(record)}>
            {t("common.edit")}
          </Button>
        </Space>
      ),
    },
  ];

  //加载表格数据
  const fetchPageList = () => {
    setLoading(true);
    packageRuleService
      .pageList(queryParams)
      .then((res) => {
        setList(res.records);
        setTotal(res.total);
      })
      .catch((error) => {
        console.log(error);
        toast.error("获取数据失败！", error);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
  useEffect(() => {
    fetchPageList();
  }, [queryParams]);

  //选择其他页
  const handlePageChange = (newPage: number, newPageSize: number) => {
    setQueryParams((prev) => ({
      ...prev,
      page: newPage,
      pageSize: newPageSize,
    }));
  };

  //触发编辑按钮
  const handleEdit = (mesPackageRule: MesPackageRule) => {
    setEditingData(mesPackageRule);
    form.setFieldsValue(mesPackageRule);
    setDrawerVisible(true);
    setIsView(false);
  };

  //触发视图按钮
  const handleView = (mesPackageRule: MesPackageRule) => {
    setEditingData(mesPackageRule);
    form.setFieldsValue(mesPackageRule);
    setIsView(true);
    setDrawerVisible(true);
  };

  //提交表单数据
  const handleSubmit = async (values: MesPackageRule) => {
    try {
      setSubmitLoading(true);

      //包装物料信息
      const deleteMaterialIds = materialRef.current?.getDeleteIds();
      const addMaterials = materialRef.current?.getAddList();
      const updateMaterials = materialRef.current?.getUpdateList();

      //包装层级数量
      const deleteTierIds = tierRef.current?.getDeleteIds();
      const addTiers = tierRef.current?.getAddList();
      const updateTiers = tierRef.current?.getUpdateList();

      const data = {
        ...values,
        id: editingData?.id,
        deleteMaterialIds: deleteMaterialIds,
        addMaterials: addMaterials,
        updateMaterials: updateMaterials,
        deleteTierIds: deleteTierIds,
        addTiers: addTiers,
        updateTiers: updateTiers,
      };
      if (editingData) {
        await packageRuleService.update(data);
        toast.success("更新包装规则成功");
      } else {
        await packageRuleService.add(data);
        toast.success("创建包装规则成功");
      }
      setDrawerVisible(false);
      setEditingData(null);
      form.resetFields();
      fetchPageList();
    } catch (error) {
      toast.error(`保存失败: ${error.message}`);
    } finally {
      setSubmitLoading(false);
    }
  };

  const handleDrawerClose = () => {
    setDrawerVisible(false);
    setEditingData(null);
    form.resetFields();
  };

  const handleAdd = () => {
    setEditingData(null);
    form.resetFields();
    setDrawerVisible(true);
    setIsView(false);
  };

  const handleDelete = async () => {
    try {
      setLoading(true);
      await packageRuleService.remove(selectedRowKeys);
      toast.success("删除包装规则成功");
      setSelectedRowKeys([]);
      fetchPageList();
    } catch (error) {
      toast.error(`删除失败: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Spin spinning={submitLoading} tip="数据提交中..." size="large">
      <Card className="mb-4">
        <Form
          layout="inline"
          onFinish={(values) => {
            setQueryParams((prev) => ({
              ...prev,
              ...values,
              page: 1,
            }));
          }}
        >
          <Form.Item name="code" label="规则编码">
            <Input placeholder="请输入规则编码" allowClear />
          </Form.Item>
          <Form.Item name="name" label="规则名称">
            <Input placeholder="请输入规则名称" allowClear />
          </Form.Item>
          <Form.Item name="type" label="规则类型">
            <Select options={typeOptions} allowClear style={{width:170}}/>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button
              className="ml-2"
              onClick={() => {
                setQueryParams({ page: 1, pageSize: 10 });
              }}
            >
              重置
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <div className="h-4" />
      <Card>
        <CustomTable
          loading={loading}
          columnsConfig={columns}
          dataSource={list}
          total={total}
          selectedRowKeys={selectedRowKeys}
          setSelectedRowKeys={setSelectedRowKeys}
          current={queryParams.page}
          pageSize={queryParams.pageSize}
          onRefresh={fetchPageList}
          onPageChange={handlePageChange}
          selectable
          toolbarButtons={
            <>
              <Button type="primary" onClick={handleAdd}>
                新增
              </Button>
              <Button
                danger
                disabled={selectedRowKeys.length === 0}
                onClick={handleDelete}
              >
                删除
              </Button>
            </>
          }
          scroll={{ y: tableScrollY }}
        />
      </Card>
      <Drawer
        title={editingData ? "编辑包装规则" : "新增包装规则"}
        width={700}
        open={drawerVisible}
        onClose={handleDrawerClose}
        footer={
          <div className="flex justify-end gap-2">
            <Button onClick={handleDrawerClose}>取消</Button>
            {!isView && (
              <Button type="primary" onClick={() => form.submit()}>
                确定
              </Button>
            )}
          </div>
        }
      >
        <Form
          form={form}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
          onFinish={handleSubmit}
          disabled={isView}
        >
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="code"
                label="规则编码"
                rules={[
                  {
                    required: true,
                    message: "请填写规则编码",
                  },
                ]}
              >
                <Input placeholder="请输入规则编码" allowClear />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="name"
                label="规则名称"
                rules={[
                  {
                    required: true,
                    message: "请填写规则名称",
                  },
                ]}
              >
                <Input placeholder="请输入规则名称" allowClear />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="type"
                label="规则类型"
                rules={[
                  {
                    required: true,
                    message: "请填写规则类型",
                  },
                ]}
              >
                <Select options={typeOptions} allowClear />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="productType" label="产品类型">
                <Input placeholder="请输入产品类型" allowClear />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={24}>
            <Col span={24}>
              <Form.Item
                name="remark"
                label="备注"
                labelCol={{ span: 3 }}
                wrapperCol={{ span: 21 }}
              >
                <Input placeholder="请输入描述" allowClear />
              </Form.Item>
            </Col>
          </Row>
          <Tabs
            defaultActiveKey="1"
            items={[
              {
                key: "1",
                label: "包装层级数量",
                children: (
                  <MesPackageRuleTierPage
                    ref={tierRef}
                    parentId={editingData?.id}
                  />
                ),
              },
              {
                key: "2",
                label: "包装物料信息",
                children: (
                  <MesPackageRuleMaterialPage
                    ref={materialRef}
                    parentId={editingData?.id}
                  />
                ),
              },
            ]}
          />
        </Form>
      </Drawer>
    </Spin>
  );
}
